/* Andreas Baum
 * DataThread.java
 * Generic proxy thread, which is used to create a tunnel
 * CS 78 - Networks
 */

package jbpClientConnector;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class DataThread extends Thread {

	private Socket socket;
	public BufferedWriter out;
	public BufferedReader in;
	private DataThread otherThread;
	private String name;
	private BufferedWriter fileOut;

	public DataThread(Socket socket, String threadName) {

		super("DataThread");
		this.socket = socket;

		// each thread has a name, for debugging purposes mainly:
		name = threadName;		
		
		try {
			fileOut = new BufferedWriter(new FileWriter(name + ".txt"));
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.exit(1);
		}
		
		try {

			out = new BufferedWriter(
					new OutputStreamWriter(socket.getOutputStream()));
			in = new BufferedReader(
					new InputStreamReader(socket.getInputStream()));

			this.start();

		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}



	}

	public void run() {

		char line;
		try {				
			// when the thread reads something it tells its "otherThread" to send it
			while ( ( ( line = (char) in.read() ) != -20) && !socket.isClosed(  ) ) {
				//System.out.println(">>> " + name+ " receiving data >>> " + line);
				otherThread.write(line);
			}
		} catch (Exception e) {
			try {
				System.err.println("!!!!!!!! " + name + " closed!!!!!!!!!!");
				e.printStackTrace();
				in.close();
				out.close();
				System.exit(1);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} 
	}

	// Each thread has an "otherThread" to which it relays everything it receives:
	public void setOtherThread(DataThread other){
		otherThread = other;
	}

	// Send data:
	public void write(char data) {
		try {
			out.write(data);
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				in.close();
				out.close();
				System.exit(1);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
		
		// The Thread also writes to a file, for debugging purposes mainly:
		try {
	        fileOut.write(data);
	    } catch (IOException e) {
	    }
	}
}